package com.gzy.xuexiziliao.filter;
import com.alibaba.fastjson.JSONObject;
import com.gzy.xuexiziliao.common.context.BaseContext;
import com.gzy.xuexiziliao.common.result.Result;
import com.gzy.xuexiziliao.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    // 定义白名单路径列表
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/login",
            "/upload",
            "/student/login",
            "/ai/imagechat"// 添加 /upload 到白名单
    );


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 1. 获取请求URL
        String url = req.getRequestURI();
        log.info("请求url:{}", url);

        // 2. 白名单放行
        if (WHITE_LIST.contains(url)) {
            chain.doFilter(request, response);
            return;
        }

        // 3. 获取令牌
        String jwt = req.getHeader("token");
        if (!StringUtils.hasLength(jwt)) {
            sendError(resp, "NOT_LOGIN");
            return;
        }
        log.info("jwt:{}", jwt);

        // 4. 解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(jwt); // 解析得到Claims
            Integer studentId = claims.get("studentId", Integer.class); // 提取studentId
            String openid = claims.get("openid", String.class);
            if (openid != null) {
                // 关键：将openid设置到BaseContext中
                BaseContext.setCurrentId(openid);
                log.info("已设置BaseContext中的当前用户: {}", openid);
            }
            req.setAttribute("studentId", studentId); // 存入请求属性
        } catch (Exception e) {
            sendError(resp, "NOT_LOGIN");
            return;
        }

        // 5. 放行
        chain.doFilter(request, response);
    }

    // 统一返回错误信息
    private void sendError(HttpServletResponse resp, String message) throws IOException {
        Result error = Result.error(message);
        String json = JSONObject.toJSONString(error);
        resp.getWriter().write(json);
    }
}